<?php
session_start();
$error = '';
$self = $_SERVER['PHP_SELF'];
if (isset($_POST['login'])) {
   //user is trying to login
   $error = checkUsernamePassword();
   if (!$error) {
      include 'db-control/dbCredentials.php';
      include 'model/Credentials.php';
      //attempt to log in
      $cred = new Credentials($_POST['username'], $_POST['pw']);
	  //$cred = new Credentials("","");
      $result = dbCredentials::login($cred);

      if (!$result) {
         $error = "Username or password is incorrect...";
      } 
	  else {
         //user is logged in
         $fname = $_SESSION['fname'];
         echo "Welcome, $fname! Log in successful!";
         forwardToURL($_SESSION['permissionLevel']);
      }
   }
}



?>
<html>
   <head>
      <title>UNHM Internships</title>
      <link rel="stylesheet" type="text/css" href="css/style.css" />
   </head>
   <body>
      <table width="100%"><div align="left">
            <tr><td rowspan="5"><img src="img/unhmlogo.png" width="200px" height="120px" /></td></tr>
            <tr><td width="80%"><h3>Login</h3><br /></td><td align="right" width="20%" valign="top"></td><td align="left" valign="top"><a href="help.php" title="View the help documentation">?</a></tr>
            <tr><td><p>Please enter your username and password:</p><hr /></td></tr>
      </table><br /><br />
      <form action ="<?php echo $self; ?>" method ="post">
         <div align="center">
            <table width="500px">
               <tr><td colspan="2"><?php echo "<p class='error'>$error</p>"; ?></td><td></td></tr>
               <tr><td align="right">Username:</td><td><input type="text" name="username" /></td></tr>
               <tr><td align="right">Password:</td><td><input type="password" name="pw" /></td></tr>
               <tr><td></td><td><input type="submit" value="Login" name="login" /></td></tr>
            </table>
         </div>
      </form>
   </body>
</html>

<?php

function forwardToURL($per){
   switch($per){
      case 1: //student
         header('Location: ' . 'view_internships.php');
         break;
      case 2: //assistant
         header('Location: ' . 'admin/');
         break;
      case 3: //administrator
         header('Location: ' . 'admin/');
         break;
   }
}

function checkUsernamePassword() {
   $username = $_POST['username'];
   $pw = $_POST['pw'];
   if ($username == '' || $pw == '') {
      $error = 'Please enter a username and password...';
   } else {
      $error = false;
   }
   return $error;
}
?>